import { reqDeleteCart, reqCheckState, reqGetCartList } from "@/api"

const state = {
    cartList: [],
}
const mutations = {
    GETCARTLIST(state, cartList) {
        state.cartList = cartList
    }
}
const actions = {
    // 获取购物车商品列表
    async getCartList({ commit }) {
        let res = await reqGetCartList()
        console.log(res);
        if (res.code === 200) {
            commit('GETCARTLIST', res.data)
        }
    },
    async deleteCart({ commit }, skuId) {
        const res = await reqDeleteCart(skuId)
        if (res.code === 200) {
            return "ok"
        }
    },
    async checkedState({ commit }, { skuId, isChecked }) {
        let res = await reqCheckState(skuId, isChecked)
        if (res.code == 200) {
            return "ok"
        }
    },
    deleteChecked({ dispatch, getters }) {
        let PromiseAll = []
        getters.cartList.cartInfoList.forEach(item => {
            let promise = item.isChecked == 1 ? dispatch('deleteCart', item.skuId) : ''
            PromiseAll.push(promise)
        })
        return Promise.all(PromiseAll)
    },
    allCartChange({ dispatch, getters }, isChecked) {
        let PromiseAll = []
        getters.cartList.cartInfoList.forEach(item => {
            let promise = dispatch('checkedState', { skuId: item.skuId, isChecked: isChecked, })
            PromiseAll.push(promise)
        })
        return Promise.all(PromiseAll)
    }
}
const getters = {
    cartList(state) {
        return state.cartList[0] || {}
    }
}
export default {
    state,
    mutations,
    actions,
    getters
}